﻿using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Win32;
using SweetWeather.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;
using Message = Vito.Csharp.Wpf.Controls;

namespace SweetWeather.ViewModel
{
    class BackGroundViewModel : NotificationObject
    {
        #region 命令
        /// <summary>
        /// 改变背景色
        /// </summary>
        public ICommand ChangeBackGround { get; set; }
        /// <summary>
        /// 保存设置
        /// </summary>
        public ICommand SaveSetting { get; set; }
        /// <summary>
        /// 获取图片列表
        /// </summary>
        public ICommand GetImagesList { get; set; }
        /// <summary>
        /// 打开自定义选择图片
        /// </summary>
        public ICommand OpenCostomImage { get; set; }
        /// <summary>
        /// 改变当前城市
        /// </summary>
        public ICommand ChangeCity { get; set; }
        /// <summary>
        /// 保存当前城市，退出时使用
        /// </summary>
        public ICommand SaveCurrentCity { get; set; }
        /// <summary>
        /// 获取所有省
        /// </summary>
        public ICommand GetProvince { get; set; }
        /// <summary>
        /// 根据省获取市
        /// </summary>
        public ICommand GetCity { get; set; }
        /// <summary>
        /// 根据市获取区
        /// </summary>
        public ICommand GetArea { get; set; }
        /// <summary>
        /// 获取添加的城市信息
        /// </summary>
        public ICommand GetAddCityInfo { get; set; }
        /// <summary>
        /// 保存添加的城市
        /// </summary>
        public ICommand SaveCity { get; set; }
        /// <summary>
        /// 获取天气信息
        /// </summary>
        public ICommand GetWeatherInfo { get; set; }
        #endregion

        #region 公有属性
        /// <summary>
        /// 自定义图片路径
        /// </summary>
        public ObservableCollection<ThemesImage> customPath { get; set; }

        /// <summary>
        /// 城市列表
        /// </summary>
        private ObservableCollection<City> cityList;
        public ObservableCollection<City> CityList
        {
            get { return cityList; }
            set { cityList = value; RaisePropertyChanged("CityList"); }
        }


        /// <summary>
        /// 是否显示清除按钮
        /// </summary>
        private Visibility isShowOpen;
        public Visibility IsShowOpen
        {
            get { return isShowOpen; }
            set { isShowOpen = value; this.RaisePropertyChanged("IsShowOpen"); }
        }


        private BackGround background;
        public BackGround BackGround
        {
            get { return background; }
            set { background = value; this.RaisePropertyChanged("BackGround"); }
        }

        /// <summary>
        /// 主题列表
        /// </summary>
        public Dictionary<string, string> ThemsesList { get; set; }

        /// <summary>
        /// 图片列表
        /// </summary>
        private ObservableCollection<ThemesImage> imageList;
        public ObservableCollection<ThemesImage> ImageList
        {
            get { return imageList; }
            set { imageList = value; this.RaisePropertyChanged("ImageList"); }
        }

        /// <summary>
        /// 省
        /// </summary>
        private ObservableCollection<City> provinceBindingList;
        public ObservableCollection<City> ProvinceBindingList
        {
            get { return provinceBindingList; }
            set { provinceBindingList = value; this.RaisePropertyChanged("ProvinceBindingList"); }
        }
        /// <summary>
        /// 市
        /// </summary>
        private ObservableCollection<City> cityBindingList;
        public ObservableCollection<City> CityBindingList
        {
            get { return cityBindingList; }
            set { cityBindingList = value; this.RaisePropertyChanged("CityBindingList"); }
        }
        /// <summary>
        /// 区
        /// </summary>
        private ObservableCollection<City> areaBindingList;
        public ObservableCollection<City> AreaBindingList
        {
            get { return areaBindingList; }
            set { areaBindingList = value; this.RaisePropertyChanged("AreaBindingList"); }
        }

        /// <summary>
        /// 默认选择请选择项
        /// </summary>
        public readonly City defaultSelectItem;
        /// <summary>
        /// 选择城市信息
        /// </summary>
        private City selectCity;
        public City SelectCity
        {
            get { return selectCity; }
            set { selectCity = value; this.RaisePropertyChanged("SelectCity"); }
        }

        /// <summary>
        /// 选择省份信息
        /// </summary>
        private City selectProvince;
        public City SelectProvince
        {
            get { return selectProvince; }
            set { selectProvince = value; this.RaisePropertyChanged("SelectProvince"); }
        }

        /// <summary>
        /// 添加城市信息
        /// </summary>
        private City addCityInfo;
        public City AddCityInfo
        {
            get { return addCityInfo; }
            set { addCityInfo = value; this.RaisePropertyChanged("AddCityInfo"); }
        }

        /// <summary>
        /// 实时天气情况
        /// </summary>
        private RealTimeWeather realTimeWeather;
        public RealTimeWeather RealTimeWeather
        {
            get { return realTimeWeather; }
            set { realTimeWeather = value; this.RaisePropertyChanged("RealTimeWeather"); }
        }

        /// <summary>
        /// 今日天气情况
        /// </summary>
        private TodayWeather todayWeather;
        public TodayWeather TodayWeather
        {
            get { return todayWeather; }
            set { todayWeather = value; this.RaisePropertyChanged("TodayWeather"); }
        }

        /// <summary>
        /// 多日天气情况
        /// </summary>
        private WeatherInfoModel moreDayWeather;
        public WeatherInfoModel MoreDayWeather
        {
            get { return moreDayWeather; }
            set { moreDayWeather = value; this.RaisePropertyChanged("MoreDayWeather"); }
        }

        /// <summary>
        /// 十四日天气情况
        /// </summary>
        private MoreDayWeatherInfoAll moreDayWeatherInfoAll;
        public MoreDayWeatherInfoAll MoreDayWeatherInfoAll
        {
            get { return moreDayWeatherInfoAll; }
            set { moreDayWeatherInfoAll = value; this.RaisePropertyChanged("MoreDayWeatherInfoAll"); }
        }


        #endregion

        #region 初始化方法
        /// <summary>
        /// 构造函数
        /// </summary>
        public BackGroundViewModel()
        {
            #region 初始化值
            this.FillThemesList();
            this.BackGround = new BackGround();
            this.GetSettingExecute();
            this.IsShowOpen = Visibility.Hidden;
            //默认加载Default
            this.FillImageList(this.BackGround.Themes);
            this.defaultSelectItem = new City { Code = "0", Name = "-请选择-" };
            #endregion

            #region 命令初始化
            this.ChangeBackGround = new DelegateCommand<string>(ChangeBackGroundExecute);
            this.SaveSetting = new DelegateCommand(SaveSettingExecute);
            this.GetImagesList = new DelegateCommand<string>(GetImagesListExecute);
            this.OpenCostomImage = new DelegateCommand(OpenCustomImageFileExecute);
            this.ChangeCity = new DelegateCommand<City>(ChangeCityExecute);
            this.SaveCurrentCity = new DelegateCommand(SaveCurrentCityExecute);
            this.GetProvince = new DelegateCommand(GetProvinceExecute);
            this.GetCity = new DelegateCommand<City>(GetCityExecute);
            this.GetArea = new DelegateCommand(GetAreaExecute);
            this.GetAddCityInfo = new DelegateCommand<City>(GetAddCityInfoExecute);
            this.SaveCity = new DelegateCommand(SaveCityExecute);
            this.GetWeatherInfo = new DelegateCommand<string>(GetWeatherInfoExecute);
            #endregion
        }

        /// <summary>
        /// 获取设置文件
        /// </summary>
        private void GetSettingExecute()
        {
            try
            {
                CityList = new ObservableCollection<City>();
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\Appconfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\Appconfig.xml");
                    var result = from res in element.Elements() select res;
                    //XmlNode fatherNode = doc.SelectSingleNode("Config");
                    //XmlNodeList root = fatherNode.ChildNodes;//查找<Theme>
                    foreach (XElement item in result)
                    {
                        if (item.Name == "DefaultImg")
                            this.BackGround.Path = item.Value;
                        else if (item.Name == "Themes")
                        {
                            this.BackGround.Themes = item.Value;
                        }
                        else if (item.Name == "ThemesCustom")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                            {
                                this.BackGround.Path = item.Value;
                                //this.ImageList.Add(new ThemesImage() { Key = name, Value = source });
                                this.customPath = new ObservableCollection<ThemesImage>() { new ThemesImage() { Key = "Custom", Value = item.Value } };
                            }
                        }
                        else if (item.Name == "RefreshMin")
                        {
                            this.BackGround.RefreshMin = item.Value;
                        }
                        else if (item.Name == "IsAutoOpen")
                        {
                            var isauto = false;
                            this.BackGround.IsAutoOpen = bool.TryParse(item.Value, out isauto) ? isauto : false;
                        }
                        else if (item.Name == "City")
                        {
                            City city = new City();
                            city.Name = item.Attribute("Name").Value;
                            city.FullName = item.Attribute("FullName").Value;
                            city.Code = item.Attribute("Code").Value;
                            this.BackGround.CurrentCity = city;
                        }
                        else if (item.Name == "CityList")
                        {
                            var cityList = from city in item.Elements("City") select city;
                            foreach (XElement city in cityList)
                            {
                                City entity = new City();
                                entity.Name = city.Attribute("Name").Value;
                                entity.FullName = city.Attribute("FullName").Value;
                                entity.Code = city.Attribute("Code").Value;
                                CityList.Add(entity);
                            }
                        }
                    }
                }
                else
                    Message.MessageBox.Show("配置文件不存在，请重新安装", "操作提示");
            }
            catch
            {
                Message.MessageBox.Show("配置文件出错，请重新安装", "操作提示");
            }
        }

        /// <summary>
        /// 保存城市到配置文件
        /// </summary>
        public void SaveCityMethod(City cityEntity)
        {
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\Appconfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\Appconfig.xml");
                    var result = from res in element.Elements("CityList") select res;
                    foreach (XElement node in result)
                    {
                        node.Add(new XElement("City", new XAttribute("Name", cityEntity.Name),
                            new XAttribute("FullName", cityEntity.FullName),
                            new XAttribute("Code", cityEntity.Code)));
                    }
                    element.Save(path + "Data\\Appconfig.xml");//保存。
                    this.BackGround.CurrentCity = cityEntity;
                    CityList.Add(cityEntity);
                }
                else
                    Message.MessageBox.Show("配置文件不存在，请重新安装", "操作提示");
            }
            catch
            {
                Message.MessageBox.Show("保存设置失败，出现异常", "操作提示");
            }
        }

        /// <summary>
        /// 填充主题
        /// </summary>
        public void FillThemesList()
        {
            this.ThemsesList = new Dictionary<string, string>();
            this.ThemsesList.Add("默认", "Default");
            this.ThemsesList.Add("扩展", "ExpandWeather");
            this.ThemsesList.Add("自定义", "Custom");
        }

        #endregion

        #region 命名对应方法
        /// <summary>
        /// 改变背景色
        /// </summary>
        private void ChangeBackGroundExecute(string bg)
        {
            this.BackGround.Path = bg;
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        private void SaveSettingExecute()
        {
            var error = this.BackGround.ErrorList;
            if (error.Count == 0)
            {
                try
                {
                    var path = System.AppDomain.CurrentDomain.BaseDirectory;
                    if (File.Exists(path + "Data\\Appconfig.xml"))
                    {
                        Thread otherad = new Thread(SaveSettingThreadMethod);
                        otherad.Priority = ThreadPriority.Highest;
                        otherad.Start();
                    }
                    else
                        Message.MessageBox.Show("配置文件不存在，请重新安装", "操作提示");
                }
                catch
                {
                    Message.MessageBox.Show("保存设置失败，出现异常", "操作提示");
                }
            }
        }

        /// <summary>
        /// 保存设置多线程
        /// </summary>
        private void SaveSettingThreadMethod()
        {
            var path = System.AppDomain.CurrentDomain.BaseDirectory;
            XmlDocument doc = new XmlDocument();
            doc.Load(path + "Data\\Appconfig.xml");
            XmlNode fatherNode = doc.SelectSingleNode("Config");
            XmlNodeList root = fatherNode.ChildNodes;//查找<Theme>
            foreach (XmlNode node in root)
            {
                XmlElement item = (XmlElement)node;
                if (item.Name == "Themes")
                {
                    item.InnerText = this.BackGround.Themes;
                }
                else if (item.Name == "ThemesCustom")
                {
                    if (this.BackGround.Themes == "Custom")
                    {
                        if (customPath != null && customPath.Count > 0 && !string.IsNullOrEmpty(customPath[0].Value))
                            item.InnerText = customPath[0].Value;
                    }
                    else
                        item.InnerText = "";
                }
                else if (item.Name == "RefreshMin")
                    item.InnerText = this.BackGround.RefreshMin;
                else if (item.Name == "IsAutoOpen")
                {
                    item.InnerText = this.BackGround.IsAutoOpen.ToString();
                    if (this.BackGround.IsAutoOpen)
                        SetAutoStart(true);
                    else
                        SetAutoStart(false);
                }
            }
            doc.Save(path + "Data\\Appconfig.xml");//保存。
        }

        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <param name="comboxValue"></param>
        private void GetImagesListExecute(string comboxValue)
        {
            this.BackGround.Themes = comboxValue;
            if (comboxValue != "Custom")
            {
                FillImageList(comboxValue);
                this.IsShowOpen = Visibility.Hidden;
            }
            //选取文件
            else
            {
                this.IsShowOpen = Visibility.Visible;
                if (customPath == null || customPath.Count == 0)
                {
                    OpenCustomImageFileExecute();
                }
                else
                {
                    this.ImageList = customPath;
                }
            }
        }

        /// <summary>
        /// 根据键值，获取图片列表
        /// </summary>
        /// <param name="key"></param>
        public void FillImageList(string key)
        {
            //this.ImageList = new Dictionary<string, string>();
            this.ImageList = new ObservableCollection<ThemesImage>();
            var path = System.AppDomain.CurrentDomain.BaseDirectory;
            if (key != "Custom")
            {
                if (File.Exists(path + "Data\\ThemeData.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\ThemeData.xml");
                    (from res in element.Elements("Theme")
                     where res.Attribute("Name").Value == key
                     select res).Elements("ThemeImg").ToList().ForEach(image =>
                     {
                         var name = image.Attribute("Name").Value;
                         var source = image.Attribute("Source").Value;
                         //this.ImageList.Add(name, source);
                         this.ImageList.Add(new ThemesImage() { Key = name, Value = source });
                     });
                }
            }
            else
            {
                this.IsShowOpen = Visibility.Visible;
                this.ImageList = customPath;
            }

        }

        /// <summary>
        /// 浏览自定义图片
        /// </summary>
        private void OpenCustomImageFileExecute()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件(*.jpg,*.jpeg,*.png,*.bmp)|*.jpg;*.jpeg;*.png;*.bmp";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            openFileDialog.ShowDialog();

            if (!String.IsNullOrEmpty(openFileDialog.FileName))
            {
                var path = openFileDialog.FileName;
                this.ImageList = new ObservableCollection<ThemesImage>();
                imageList.Add(new ThemesImage() { Key = "Custom", Value = path });
                customPath = imageList;
                this.BackGround.Path = path;
            }
        }

        /// <summary>
        /// 改变目标城市
        /// </summary>
        private void ChangeCityExecute(City city)
        {
            this.BackGround.CurrentCity = city;
            Thread otherad = new Thread(GetAllWeathInfo);
            otherad.Priority = ThreadPriority.Highest;
            otherad.Start();
        }

        /// <summary>
        /// 获取所有天气信息【多线程】
        /// </summary>
        private void GetAllWeathInfo()
        {
            GetWeatherInfoExecute(EnumGetWeatherMothod.All.ToString());
        }

        /// <summary>
        /// 保存当前城市
        /// </summary>
        public void SaveCurrentCityExecute()
        {
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\Appconfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\Appconfig.xml");
                    var result = from res in element.Elements("City") select res;
                    var first = result.FirstOrDefault();
                    if (first != null)
                    {
                        first.ReplaceWith(new XElement("City", new XAttribute("Name", this.BackGround.CurrentCity.Name),
                        new XAttribute("FullName", this.BackGround.CurrentCity.FullName),
                        new XAttribute("Code", this.BackGround.CurrentCity.Code)));
                    }
                    element.Save(path + "Data\\Appconfig.xml");//保存。
                }
                else
                    Message.MessageBox.Show("配置文件不存在，请重新安装", "操作提示");
            }
            catch
            {
                Message.MessageBox.Show("保存设置失败，出现异常", "操作提示");
            }
        }

        /// <summary>
        /// 设置程序开机启动
        /// 或取消开机启动
        /// </summary>
        /// <param name="started">设置开机启动，或者取消开机启动</param>
        /// <param name="exeName">注册表中程序的名字</param>
        /// <param name="path">开机启动的程序路径</param>
        /// <returns>开启或则停用是否成功</returns>
        public bool SetAutoStart(bool started)
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                String name = Process.GetCurrentProcess().MainModule.FileName;
                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项
                if (key == null)//如果该项不存在的话，则创建该子项
                {
                    key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                if (started == true)
                {
                    try
                    {
                        key.SetValue("SweetWeather", name);//设置为开机启动
                        key.Close();
                    }
                    catch (Exception ex)
                    {
                        Message.MessageBox.Show(ex.ToString(), "提示信息");
                        return false;
                    }
                }
                else
                {
                    try
                    {
                        key.DeleteValue("SweetWeather");//取消开机启动
                        key.Close();
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 获取省
        /// </summary>
        private void GetProvinceExecute()
        {
            if (provinceBindingList == null || provinceBindingList.Count == 0)
            {
                var province = AreaManager.GetProvince();
                province.Insert(0, defaultSelectItem);
                ProvinceBindingList = new ObservableCollection<City>(province);
            }
            else
            {
                SelectProvince = defaultSelectItem;
                SelectCity = defaultSelectItem;
            }
        }

        /// <summary>
        /// 获取市
        /// </summary>
        /// <param name="obj"></param>
        private void GetAreaExecute()
        {
            if (SelectCity != null && SelectCity.Code != "0")
            {
                var area = AreaManager.GetAreaByCID(SelectCity);
                area.Insert(0, defaultSelectItem);
                AreaBindingList = new ObservableCollection<City>(area);
            }
            else if (SelectCity == null || SelectCity != null && SelectCity.Code == "0")
                AreaBindingList = new ObservableCollection<City>(new List<City>() { defaultSelectItem });
        }

        /// <summary>
        /// 获取区
        /// </summary>
        /// <param name="obj"></param>
        private void GetCityExecute(City province)
        {
            if (province != null && province.Code != "0")
            {
                var city = AreaManager.GetCityByPID(province);
                city.Insert(0, defaultSelectItem);
                CityBindingList = new ObservableCollection<City>(city);
                SelectCity = defaultSelectItem;
            }
            else if (province == null || province != null && province.Code == "0")
                CityBindingList = new ObservableCollection<City>(new List<City>() { defaultSelectItem });
        }

        /// <summary>
        /// 获取添加的城市信息
        /// </summary>
        /// <param name="obj"></param>
        private void GetAddCityInfoExecute(City obj)
        {
            AddCityInfo = obj;
        }

        /// <summary>
        /// 保存城市命令
        /// </summary>
        private void SaveCityExecute()
        {
            if (AddCityInfo != null && AddCityInfo.Code != "0")
            {
                SaveCityMethod(AddCityInfo);
            }
            else
                Message.MessageBox.Show("请选择具体的城市区域!", "操作提示");
        }

        /// <summary>
        /// 获取天气情况
        /// </summary>
        /// <param name="obj"></param>
        public void GetWeatherInfoExecute(string obj)
        {
            switch (obj)
            {
                case "RealTime":
                    this.RealTimeWeather = WeatherInfoManager.GetRealTimeWeather(this.BackGround.CurrentCity.Code);
                    break;
                case "Today":
                    this.TodayWeather = WeatherInfoManager.GetTodayWeather(this.BackGround.CurrentCity.Code);
                    GetWeatherBackGround(TodayWeather.weather, DateTime.Now.Hour);
                    break;
                case "MoreDay":
                    this.MoreDayWeather = WeatherInfoManager.GetMoredayWeather(this.BackGround.CurrentCity.Code);
                    break;
                case "All":
                    this.RealTimeWeather = WeatherInfoManager.GetRealTimeWeather(this.BackGround.CurrentCity.Code);
                    this.TodayWeather = WeatherInfoManager.GetTodayWeather(this.BackGround.CurrentCity.Code);
                    GetWeatherBackGround(TodayWeather.weather, DateTime.Now.Hour);
                    this.MoreDayWeatherInfoAll = WeatherInfoManager.GetFourteenDayWeather(this.BackGround.CurrentCity.Name);
                    this.MoreDayWeather = WeatherInfoManager.GetMoredayWeather(this.BackGround.CurrentCity.Code);
                    break;
            }
            this.BackGround.LastUpdateTime = DateTime.Now;
        }

        /// <summary>
        /// 根据天气名称和时间，改变背景图
        /// </summary>
        /// <param name="WeatherName">天气名称</param>
        /// <param name="hour">小时数</param>
        public void GetWeatherBackGround(string WeatherName, int hour)
        {
            if (this.BackGround.Themes == "Custom")
                return;
            var img = "q";
            if (WeatherName.Contains("雪"))
                img = "x";
            else if (WeatherName.Contains("雨"))
                img = "y";
            else if (WeatherName.Contains("冰雹"))
                img = "bb";
            else if (WeatherName.Contains("阴"))
                img = "y";
            else if (WeatherName.Contains("雾") || WeatherName.Contains("霾"))
                img = "w";
            else if (WeatherName.Contains("尘"))
                img = "fc";
            else if (WeatherName.Contains("多云"))
                img = "dy";
            else if (WeatherName.Contains("晴"))
                img = "q";
            else
                img = "q";
            if (hour >= 5 && hour <= 19)
                img += "-b";
            else
                img += "-h";
            this.ChangeBackGroundExecute(string.Format("../images/{0}/{1}.JPG", this.BackGround.Themes, img));
        }
        #endregion

    }
}
